// src/mqttService.js
import mqtt from 'mqtt'
import { useAirStore } from '@/stores'
class MqttService {
  constructor() {
    this.client = null
  }

  connect() {
    const airStore = useAirStore()
    this.client = mqtt.connect(MqttConfig.brokerUrl, {
      username: MqttConfig.Username,
      password: MqttConfig.Password
    })

    this.client.on('connect', () => {
      console.log('连接成功')
    })

    this.client.on('message', (topic, message) => {
      console.log('收到消息：', topic, message.toString())
      let receive = JSON.parse(message)
      if (topic.includes('uavRealDataReq')) {
        receive.forEach((item) => {
          airStore.AirFlight[item.snId] = item
        })
      }
      // if (topic.includes('uavRealAlarmReq')) {
      //   receive.forEach((item) => {
      //     airStore.AirAlarm[item.airSn] = item
      //   })
      // }
    })
  }

  subscribe(topic) {
    if (this.client) {
      this.client.subscribe(topic, (err) => {
        if (!err) {
          console.log(`成功订阅：${topic}`)
        }
      })
    }
  }

  publish(topic, message) {
    if (this.client) {
      this.client.publish(topic, message)
    }
  }
}

export default MqttService
